package com.layui.ad.controller;

import com.alibaba.fastjson.JSON;
import com.layui.ad.constant.DictConstant;
import com.layui.ad.entity.Article;
import com.layui.ad.query.ArticleQuery;
import com.layui.ad.service.ArticleService;
import com.layui.ad.utils.HttpClientUtil;
import com.layui.ad.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/article")
public class ArticleController extends BaseController {

    @Autowired
    private ArticleService articleService;

    @RequestMapping("index")
    public String index(HttpServletRequest request) {
        request.setAttribute("articleStatusList",DictConstant.ARTICLE_STATUS_LIST);
        return "article/index";
    }

    @ResponseBody
    @PostMapping("list")
    public JsonResult list(ArticleQuery articleQuery) {
        return articleService.getList(articleQuery);
    }

    @GetMapping("/edit")
    public String edit(HttpServletRequest request, Integer id) {
        Map<String, String> info = new HashMap<>();
        String[] imgList = new String[]{};
        if (null != id && id > 0) {
            info = articleService.info(id);
        }
        String imgs = info.get("imgs");
        if(null != imgs){
            imgList = imgs.split(",");
        }
        request.setAttribute("info", info);
        request.setAttribute("imgList", Arrays.asList(imgList));
        request.setAttribute("statusList", DictConstant.ARTICLE_STATUS_LIST);
        return "article/edit";
    }

    @ResponseBody
    @PostMapping("add")
    public JsonResult add(@RequestBody Article article) {
        return articleService.edit(article);
    }


    @ResponseBody
    @PostMapping("update")
    public JsonResult update(@RequestBody Article article){
        return  articleService.edit(article);
    }

    @ResponseBody
    @GetMapping("delete/{id}")
    public JsonResult delete(@PathVariable("id") Integer id){
        return articleService.delete(id);
    }

    @ResponseBody
    @GetMapping("batchDelete/{ids}")
    public JsonResult batchDelete(@PathVariable("ids") String ids){
        return articleService.batchDelete(ids);
    }


    @ResponseBody
    @GetMapping("code")
    public JsonResult code(){
        String code  = HttpClientUtil.sendHttpGet("http://appapi.5i5j.com/brokerinfiltration/getusermobile?code=63948653");
        Map<String,Object> recordResult = new HashMap<>();
        recordResult =JSON.parseObject(code);
        System.out.println(recordResult.get("data"));
        System.out.println(code);
        return JsonResult.ok();
    }

}
